package model

import (
	"time"
	"user_srv/basic/config"
)

// 用户灵魂问答答案表
type XqUserSoulAnswers struct {
	Id          int64     `gorm:"column:id;type:bigint(20);comment:记录ID;primaryKey;not null;" json:"id"`
	UserId      int64     `gorm:"column:user_id;type:bigint(20);comment:用户ID;not null;" json:"user_id"`
	QuestionId  int64     `gorm:"column:question_id;type:bigint(20);comment:题目ID;not null;" json:"question_id"`
	Answer      string    `gorm:"column:answer;type:json;comment:用户答案(JSON格式);not null;" json:"answer"`
	AnswerScore float64   `gorm:"column:answer_score;type:decimal(5,2);comment:答案分数;" json:"answer_score"`
	AnsweredAt  time.Time `gorm:"column:answered_at;type:timestamp;comment:答题时间;not null;default:CURRENT_TIMESTAMP;" json:"answered_at"`
}

func (x *XqUserSoulAnswers) TableName() string {
	return "xq_user_soul_answers"
}

func (x *XqUserSoulAnswers) Create() error {
	return config.DB.Create(&x).Error
}

func (x *XqUserSoulAnswers) Delete(where XqUserSoulAnswers) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqUserSoulAnswers) Update(where XqUserSoulAnswers) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqUserSoulAnswers) List(where XqUserSoulAnswers) ([]XqUserSoulAnswers, error) {
	var answers []XqUserSoulAnswers
	err := config.DB.Where(where).Find(&answers).Error
	return answers, err
}

func (x *XqUserSoulAnswers) GetByUserAndQuestion(userId, questionId int64) (*XqUserSoulAnswers, error) {
	var answer XqUserSoulAnswers
	err := config.DB.Where("user_id = ? AND question_id = ?", userId, questionId).First(&answer).Error
	return &answer, err
}

func (x *XqUserSoulAnswers) ListByUserId(userId int64) ([]XqUserSoulAnswers, error) {
	var answers []XqUserSoulAnswers
	err := config.DB.Where("user_id = ?", userId).Order("answered_at DESC").Find(&answers).Error
	return answers, err
}

func (x *XqUserSoulAnswers) HasAnswered(userId, questionId int64) bool {
	var count int64
	config.DB.Model(&XqUserSoulAnswers{}).Where("user_id = ? AND question_id = ?", userId, questionId).Count(&count)
	return count > 0
}
